<template>
  <div id="app">
    <!-- <van-row> -->
    <Subscribe />
    <div class="bottom-gap">
        <Navbar v-if="$router.routerQueue.length>1"/>
        <keep-alive>
          <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive"></router-view>
        <y-tabbar></y-tabbar>
        <Loading v-show="LOADING" />
    </div>
  </div>
</template>

<script>
import router from "./router.js";
import YTabbar from "./components/YTabbar.vue";
import Loading from "./components/Loading.vue";
import Navbar from "./components/Navbar.vue";
import Subscribe from "./components/Subscribe.vue"; //检测是否关注公众号
import { config } from "./config.js";
import store from "./store";
import { mapState } from "vuex";
import { Toast } from 'vant'
export default {
  name: "app",
  components: {
    YTabbar,
    Loading,
    Navbar,
    Subscribe
  },
  data() {
    return {};
  },
  router,
  store,
  mounted() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.includes("micromessenger")) {
      console.log(
        "%cBingo＜（＾－＾）＞你已经在微信登陆",
        "color:#123;background-color:#eee;font-size:20px;border:1px solid #123;border-radius:15px;"
      );
    } else {
      setTimeout(() => {
          Toast({
            message:'ئۈندىداردا ئېچىڭ',
            duration:1000
          })
      }, 2000);
      window.close();
    }
    this.getUserInfo();
  },
  methods: {
    getUserInfo() {
      let userInfo = window.localStorage.getItem("userInfo");
      if (!this.validUserInfo(userInfo)) {
        let code = this.GetQueryString("code");
        if (!code) {
          let redirect = window.encodeURIComponent(window.location.origin);
          try {
            window.location.assign(
              `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.appid}&redirect_uri=${redirect}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
            );
          } catch (error) {}
        } else {
          this.$http
            .get("/wx_login?code=" + this.GetQueryString("code"))
            .then(res => {
              if(!res.oldUser){
                this.$http
                  .post("/setUserInfo", {
                    userInfo: JSON.stringify(res)
                  })
                  .then(result => {
                    window.localStorage.setItem(
                      "userInfo",
                      JSON.stringify({uid: result.userInfo.uid ,openid: result.userInfo.openid })
                    );
                    this.$store.commit('SET_USERINFO',result.userInfo);
                    this.$store.state.isSubscribe = result.userInfo.subscribe ? result.userInfo.subscribe : 0
                  });
              }
              else {
                this.$store.commit('SET_USERINFO',res);
                this.$store.state.isSubscribe = res.subscribe ? res.subscribe : 0
                window.localStorage.setItem(
                      "userInfo",
                      JSON.stringify({uid: res.uid ,openid: res.openid })
                    );
              }
            });
        }
      } else {
        this.handleSubscribe(JSON.parse(userInfo));
        let self= this;
        document.addEventListener("visibilitychange", function() {
          if(document.visibilityState=='visible'){
            self.handleSubscribe(JSON.parse(userInfo))
          }
        });
      }
    },
    GetQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    parseUserInfo(data) {
      try {
        let info = JSON.parse(data);
        if (info.errcode) {
          return false;
        }
        return JSON.parse(data);
      } catch (error) {
        return false;
      }
    },
    // 判断是否为有效的用户信息
    validUserInfo(info){
        try {
            let userInfo = JSON.parse(info);
            if(!userInfo.openid || !userInfo.uid){
                return false;
            }
            return true;
        } catch (error) {
            return false;
        }
    },
    // 判断用户没有关注公众号
    handleSubscribe(userInfo){
        this.$http.get('/getBaseInfo', {
            params:{ openid: userInfo.openid }
        }).then(res=> {
          try {
            let userInfo = JSON.parse(this.$decrypt(res));
            if (userInfo.endTime && userInfo.endTime > Date.now()) {
                    userInfo.isVip = 1;
            }
            this.$store.commit('SET_USERINFO',userInfo);
            this.$store.state.isSubscribe = userInfo.subscribe
          } catch (error) {
            this.$store.state.isSubscribe = 0;
          }
        })
    }
  },
  computed: {
    ...mapState(["LOADING"])
  },
  watch: {}
};
</script>
<style lang="scss">
@import url("./static/css/icon.css");
@import url("./static/css/font.css");
// @import url("./static/css/_common.scss");
#app {
  margin: 0 auto;
  font-family: "ALKATIP UI";
  text-align: center;
  color: #2c3e50;
  .bottom-gap {
    padding-bottom: 170px;
  }
}
.van-toast {
  div {
    transform: translateY(3px);
  }
}
.vue-waterfall{
  div.vue-waterfall-column:nth-of-type(3){
    img {
      float: left;
    }
  }
  div.vue-waterfall-column:nth-of-type(3){
    img{
      float: right
    }
  }
}
</style>

<!-- 
  Token:      BPnp8jAu0pHp4o5uLJj4HxD7DZ4ou7tL
  EncodingAESKey:           SKQGMJWIM2xP2qxrwQk0W1kWGQ22XiXQgGR2b0z0eXW

 -->